package com.car.util;

import java.rmi.activation.ActivationException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.zip.DataFormatException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * andy.Luo
 */
public final class DateUtil {
	private static Log log = LogFactory.getLog(DateUtil.class);

	private static final SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
	private static SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd");

	private DateUtil() {
	}

	/**
	 * 获取今天开始时间
	 * 
	 * @return
	 */
	public static Date getTodayStartTime() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		Date start = calendar.getTime();
		return start;
	}

	/**
	 * 获取本周第一天时间
	 * 
	 * @return
	 */
	public static Date getFirstDayCurrWeek() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		Date start = calendar.getTime();
		return start;
	}

	/**
	 * 获取本月第一天时间
	 * 
	 * @return
	 */
	public static Date getFirstDayCurrMonth() {

		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DATE, 1);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		Date start = calendar.getTime();
		return start;
	}

	/**
	 * 获取今天剩余秒速
	 * 
	 * @return
	 */
	public static Long getTodayRemainSeconds() {

		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);

		// Date nextday = calendar.getTime();
		Long seconds = calendar.getTimeInMillis() - System.currentTimeMillis();
		return seconds / 1000;
	}

	/**
	 * 获取当前小时剩余秒数 by hq
	 * 
	 * @return
	 */
	public static Long getHourRemainSeconds() {

		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);

		// Date nextday = calendar.getTime();
		Long seconds = calendar.getTimeInMillis() - System.currentTimeMillis();
		return seconds / 1000;
	}

	/**
	 * Date->String
	 * 
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String dateToStr(Date date, String pattern) {
		SimpleDateFormat formater2 = new SimpleDateFormat(pattern);
		if (date == null) {
			return "";
		}
		return formater2.format(date);
	}

	/**
	 * convert string to date ,with custom pattern,throws IllegalArgumentException
	 * 
	 * @param str
	 * @param format
	 * @return
	 */
	public static Date str2Date(String str, String format) {
		SimpleDateFormat formater = new SimpleDateFormat(format);
		Date date = null;
		try {
			date = formater.parse(str);
		} catch (ParseException e) {
			//
		}
		return date;
	}

	/**
	 * convert string to date, with default pattern,throws ParseException
	 * 
	 * @param str
	 * @return
	 */
	public static Date str2Date(String str) {
		Date date = null;
		try {
			date = formater.parse(str);
		} catch (ParseException e) {
			//
		}
		return date;
	}

	/**
	 * convert date to string,with custom pattern,throws IllegalArgumentException
	 * 
	 * @param date
	 * @param format
	 * @return
	 */
	public static String date2Str(Date date, String format) {
		SimpleDateFormat formater = new SimpleDateFormat(format);
		if (date != null) {
			return formater.format(date);
		} else {
			return "";
		}
	}

	/**
	 * convert date to string,with default pattern
	 * 
	 * @param date
	 * @return
	 */
	public static String date2Str(Date date) {
		if (date != null) {
			return formater.format(date);
		} else {
			return "";
		}

	}

	/**
	 * 由日期,小时,分,钟组合成一个 yyyy-MM-dd hh:mm:ss 格式的 Date object
	 * 
	 * @param date
	 * @param hours
	 * @param minutes
	 * @param seconds
	 * @return
	 */
	public static Date str2Date(String date, String hours, String minutes, String seconds) {
		String secondsNew = seconds;
		if (null == date || "".equals(date) || null == hours || "".equals(hours) || null == minutes
				|| "".equals(minutes)) {
			return null;
		}
		if (null == secondsNew) {
			secondsNew = "00";
		}
		Date retDate = null;
		StringBuffer dateBuffer = new StringBuffer(date);
		dateBuffer.append(" ").append(hours).append(":").append(minutes).append(":").append(secondsNew);
		retDate = str2Date(dateBuffer.toString(), "yyyy-MM-dd HH:mm:ss");
		return retDate;
	}

	/**
	 * ****************************** denny up && ye.li down
	 * *****************************
	 */

	/**
	 * String->Date
	 * 
	 * @param str
	 * @param pattern
	 * @return
	 */
	public static Date strToDate(String str, String pattern) {
		Date dateTemp = null;
		SimpleDateFormat formater2 = new SimpleDateFormat(pattern);
		try {
			dateTemp = formater2.parse(str);
		} catch (Exception e) {
			log.error("exception in convert string to date!");
		}
		return dateTemp;
	}

	/**
	 * input "2006-8",output "2006-08-01 00:00:00"
	 * 
	 * @author denny 2006-11-1
	 * @param dateStr
	 * @return
	 */
	public static Date getStartMonth(String dateStr) {
		return strToDate(dateStr, "yyyy-MM");
	}

	/**
	 * input "2006-8",output "2006-09-01 00:00:00"
	 * 
	 * @author denny 2006-11-1
	 * @param dateStr
	 * @return
	 */
	public static Date getEndMonth(String dateStr) {
		Date d = strToDate(dateStr, "yyyy-MM");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.MONTH, 1);
		return new Date(date.getTimeInMillis());
	}

	/**
	 * input "2006-8",output "2006-7"
	 * 
	 * @author denny 2006-11-1
	 * @param dateStr
	 * @return
	 */
	public static String getBeforeMonth(String dateStr) {
		Date d = strToDate(dateStr, "yyyy-MM");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.MONTH, -1);
		return dateToStr(new Date(date.getTimeInMillis()), "yyyy-MM");
	}

	/**
	 * input "2006-08-01 00:00:00",output "2006-07-01 00:00:00"
	 * 
	 * @return
	 */
	public static Date getBeforeMonthDate(Date dateStr, int n) {
		Calendar date = Calendar.getInstance();
		date.setTime(dateStr);
		date.add(Calendar.MONTH, -n);
		return date.getTime();
	}

	/**
	 * @return 获取昨天日期
	 */
	public static Date getBeforeDay() {
		String dateStr = getStringDate("yyyy-MM-dd");
		Date d = strToDate(dateStr, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, -1);
		return new Date(date.getTimeInMillis());
	}

	/**
	 * @return 获取前天日期
	 */
	public static Date getBeforetwoDay() {
		String dateStr = getStringDate("yyyy-MM-dd");
		Date d = strToDate(dateStr, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, -2);
		return new Date(date.getTimeInMillis());
	}

	public static Date getBeforeDay4(Date today) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 日期格式
		String dateFormart = df.format(today);
		Date d = strToDate(dateFormart, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, -4);
		return new Date(date.getTimeInMillis());
	}

	public static Date getBeforeDay(Date today) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 日期格式
		String dateFormart = df.format(today);
		Date d = strToDate(dateFormart, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, -1);
		return new Date(date.getTimeInMillis());
	}

	/**
	 * @return 获取前天日期
	 */
	public static Date getBeforetwoDay(Date today) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 日期格式
		String dateFormart = df.format(today);
		Date d = strToDate(dateFormart, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, -2);
		return new Date(date.getTimeInMillis());
	}

	// 获取大前天日期
	public static Date getBeforetwoDay3(Date today) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 日期格式
		String dateFormart = df.format(today);
		Date d = strToDate(dateFormart, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, -3);
		return new Date(date.getTimeInMillis());
	}

	// 获取5天前日期
	public static Date getBeforetwoDay5(Date today) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 日期格式
		String dateFormart = df.format(today);
		Date d = strToDate(dateFormart, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, -5);
		return new Date(date.getTimeInMillis());
	}

	/**
	 * @return 获取明天日期
	 * 
	 */
	public static Date getTommorrowDay() {
		String dateStr = getStringDate("yyyy-MM-dd");
		Date d = strToDate(dateStr, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, +1);
		return new Date(date.getTimeInMillis());
	}
	
	public static long getTommorrowDay_Ms() {
		String dateStr = getStringDate("yyyy-MM-dd");
		Date d = strToDate(dateStr, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, +1);
		return date.getTimeInMillis();
	}

	/**
	 * @return 获取明天日期
	 * 
	 */
	public static Date getTommorrowDay1(Date today) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 日期格式
		String dateFormart = df.format(today);
		Date d = strToDate(dateFormart, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, +1);
		return new Date(date.getTimeInMillis());
	}

	public static Date getTommorrowDay2(Date today) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 日期格式
		String dateFormart = df.format(today);
		Date d = strToDate(dateFormart, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, +2);
		return new Date(date.getTimeInMillis());
	}

	// 获取后天日期
	public static Date getTommorrowDay3(Date today) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 日期格式
		String dateFormart = df.format(today);
		Date d = strToDate(dateFormart, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, +3);
		return new Date(date.getTimeInMillis());
	}

	public static Date getTommorrowDay4(Date today) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 日期格式
		String dateFormart = df.format(today);
		Date d = strToDate(dateFormart, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, +4);
		return new Date(date.getTimeInMillis());
	}

	/**
	 * 获取指定一天的开始
	 * 
	 * @param time
	 * @return
	 */
	public static Date getStartTime(Date time, String format) {
		SimpleDateFormat df = new SimpleDateFormat(format);// 日期格式
		String dateFormart = df.format(time);
		Date d = strToDate(dateFormart, format);
		return d;
	}

	/**
	 * @return 获取今天日期
	 */
	public static Date getToDay() {
		String dateStr = getStringDate("yyyy-MM-dd");
		Date d = strToDate(dateStr, "yyyy-MM-dd");
		return d;
	}

	/**
	 * input 2006,8 output "2006-08"
	 * 
	 * @author liye 2006-11-1
	 * @param intYear
	 * @param intMonth
	 * @return
	 */
	public static String getYearMonth(int intYear, int intMonth) {
		String str = "" + intYear + "-" + intMonth;
		return str;
	}

	/**
	 * input 2006,8,20 output "2006-8-20"
	 * 
	 * @author ye.li 2006-12-31
	 * @param intYear
	 * @param intMonth
	 * @param intDay
	 * @return
	 */
	public static String getStringDate(int intYear, int intMonth, int intDay) {
		String str = "" + intYear + "-" + intMonth + "-" + intDay;
		return str;
	}

	/**
	 * input 2006,8,2 output "2006-08-02"
	 * 
	 * @author ye.li 2007-1-5
	 * @param intYear
	 * @param intMonth
	 * @param intDay
	 * @return
	 */
	public static String getStandardStringDate(int intYear, int intMonth, int intDay) {
		String str = intToStandardString(intYear) + "-" + intToStandardString(intMonth) + "-"
				+ intToStandardString(intDay);
		return str;
	}

	/**
	 * input 2 output "02"
	 * 
	 * @author ye.li 2007-1-5
	 * @param intNum
	 * @return
	 */
	public static String intToStandardString(int intNum) {
		if (intNum >= 0 && intNum < 10) {
			return "0" + intNum;
		} else {
			return "" + intNum;
		}
	}

	/**
	 * 将星期的数字转换为汉语
	 * 
	 * @author ye.li
	 * @param intWeek
	 * @return
	 */
	public static String convWeek(int intWeek) {
		String strWeek = null;
		switch (intWeek) {
		case 0:
			strWeek = "日";
			break;
		case 1:
			strWeek = "一";
			break;
		case 2:
			strWeek = "二";
			break;
		case 3:
			strWeek = "三";
			break;
		case 4:
			strWeek = "四";
			break;
		case 5:
			strWeek = "五";
			break;
		case 6:
			strWeek = "六";
			break;
		default:
			break;
		}

		return strWeek;
	}

	/**
	 * 2016年5月26日 lvjianqing 得到今天星期几
	 */
	public static int getWeek() {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;
		return w;
	}

	/**
	 * 2016年5月26日 lvjianqing 得到当前日期星期几
	 */
	public static int getDateWeek(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;
		return w;
	}

	/**
	 * @author Power Wang
	 * @return Return a timestamp object
	 */
	public static Timestamp getATimeStamp() {
		Calendar date = Calendar.getInstance();
		date.add(Calendar.YEAR, 10);
		return new Timestamp(date.getTimeInMillis());
	}

	/**
	 * @author Alex Su
	 * @param startTime
	 * @param duringTime
	 * @return Return a Date object
	 */
	public static Date getEndTime(Date startTime, Integer duringTime) {
		// duringTime :以分钟为单位
		Calendar date = Calendar.getInstance();
		date.setTime(startTime);
		date.add(Calendar.MINUTE, duringTime);
		return date.getTime();
	}

	/**
	 * 
	 * @param date
	 * @param formaterString
	 * @return date
	 */
	public static Date formatDate(Date date, String formaterString) {

		SimpleDateFormat sFormater = new SimpleDateFormat(formaterString);
		String tempDate = sFormater.format(date);
		Date result = date;// 转换失败 不做改变
		try {
			result = sFormater.parse(tempDate);
		} catch (ParseException e) {
			throw new RuntimeException("字符串转换成日期出错", e);
		}

		return result;

	}

	public static Timestamp date2DateTime(Date date) {
		Timestamp time = new Timestamp(date.getTime());
		return time;
	}

	/**
	 * 比较两个时间相差多少天
	 * 
	 * @param nowdate
	 * @param inputdate
	 * @return
	 * @throws DataFormatException
	 * @throws ActivationException
	 */
	public static long DateDiff(Date nowdate, Date inputdate) throws DataFormatException, ActivationException {
		long nowTime;
		long diffTime;
		long days = 0;
		if (nowdate == null || inputdate == null) {
			return days;
		}
		try {
			nowTime = (nowdate.getTime() / 1000);
			diffTime = (inputdate.getTime() / 1000);
			if (nowTime > diffTime) {
				days = (nowTime - diffTime) / (1 * 60 * 60 * 24);
			} else {
				days = (diffTime - nowTime) / (1 * 60 * 60 * 24);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return days;

	}

	/*
	 * 当天日期增加或减少几天
	 */
	public static Date DateAdd(Date date, int datediff) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DATE, datediff);
		Date times = calendar.getTime();
		return times;
	}

	public static Integer CalendarAdd(int datediff) {
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, datediff);
		int day = calendar.get(Calendar.DATE);
		return day;
	}

	/**
	 * 当天日期增加或减少几月
	 */
	public static Date MonthAdd(Date date, int datediff) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MONTH, datediff);
		Date times = calendar.getTime();
		return times;
	}

	/**
	 * 获取当前年份
	 * 
	 * @return
	 */
	public static int getYear() {

		SimpleDateFormat df = new SimpleDateFormat("yyyy");// 日期格式
		int year = Integer.parseInt(df.format(new Date()));

		return year;

	}

	public static Long getDiffHour(Date nowTime, Date diffTime) {

		Long nowTimes = nowTime.getTime() / 1000;
		Long diffTimes = diffTime.getTime() / 1000;
		Long diff = (diffTimes - nowTimes) / (1 * 60 * 60);

		return diff;

	}

	public static Date getDate() {

		Date date = new Date();
		return date;
	}

	public static String getStringDate(String formart) {
		SimpleDateFormat df = new SimpleDateFormat(formart);// 日期格式
		String dateFormart = df.format(new Date());
		return dateFormart;
	}

	// 向后推时间(单位月)
	public static String getStringDiffDate(String formart, int num) {
		String reStr = "";
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String str = formart;
			Date dt = sdf.parse(str);
			Calendar rightNow = Calendar.getInstance();
			rightNow.setTime(dt);
			rightNow.add(Calendar.YEAR, 0);// 日期减1年
			rightNow.add(Calendar.MONTH, num);// 日期加3个月
			rightNow.add(Calendar.DAY_OF_YEAR, 0);// 日期加10天
			Date dt1 = rightNow.getTime();
			reStr = sdf.format(dt1);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return reStr;
	}

	//
	public static String getStringDiffDate(String formart, int numMonth, int numDay) {
		String reStr = "";
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String str = formart;
			Date dt = sdf.parse(str);
			Calendar rightNow = Calendar.getInstance();
			rightNow.setTime(dt);
			rightNow.add(Calendar.YEAR, 0);// 日期减1年
			rightNow.add(Calendar.MONTH, numMonth);// 日期加3个月
			rightNow.add(Calendar.DAY_OF_YEAR, numDay);// 日期加10天
			Date dt1 = rightNow.getTime();
			reStr = sdf.format(dt1);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return reStr;
	}

	public static Date getStringDiffDate(Date date, int numDay) {
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(date);
		rightNow.add(Calendar.YEAR, 0);// 日期减1年
		rightNow.add(Calendar.MONTH, 0);// 日期加3个月
		rightNow.add(Calendar.DAY_OF_YEAR, numDay);// 日期加10天
		Date dt1 = rightNow.getTime();
		return dt1;
	}

	// 向后推时间(单位月)
	public static Date getDiffDate(String formart, int num) {
		Date dt1 = new Date();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String str = formart;
			Date dt = sdf.parse(str);
			Calendar rightNow = Calendar.getInstance();
			rightNow.setTime(dt);
			rightNow.add(Calendar.YEAR, 0);// 日期减
			rightNow.add(Calendar.MONTH, num);// 日期加
			rightNow.add(Calendar.DAY_OF_YEAR, 0);// 日期加
			dt1 = rightNow.getTime();

		} catch (ParseException e) {
			e.printStackTrace();
		}
		return dt1;
	}

	// 向前推时间（单位天）
	public static String getStringDiffDateOfDay(String formart, int num) {

		Calendar curr = Calendar.getInstance();
		curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) + num);
		Date date = curr.getTime();
		SimpleDateFormat df = new SimpleDateFormat(formart);// 日期格式
		String dateFormart = df.format(date);
		return dateFormart;
	}

	/**
	 * @date 2013年6月8日 向前推一个月 lvjq
	 */
	public static String lastMonth() {
		Date date = new Date();
		int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));
		int month = Integer.parseInt(new SimpleDateFormat("MM").format(date)) - 1;
		int day = Integer.parseInt(new SimpleDateFormat("dd").format(date));

		if (month == 0) {
			year -= 1;
			month = 12;
		} else if (day > 28) {
			if (month == 2) {
				if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
					day = 29;
				} else
					day = 28;
			} else if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
				day = 30;
			}
		}
		String y = year + "";
		String m = "";
		String d = "";
		if (month < 10)
			m = "0" + month;
		else
			m = month + "";
		if (day < 10)
			d = "0" + day;
		else
			d = day + "";
		return y + "-" + m + "-" + d;
	}

	public static String lastMonth2() {
		Date date = new Date();
		int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));
		int month = Integer.parseInt(new SimpleDateFormat("MM").format(date)) - 1;
		int day = Integer.parseInt(new SimpleDateFormat("dd").format(date));

		if (month == 0) {
			year -= 1;
			month = 12;
		} else if (day > 28) {
			if (month == 2) {
				if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
					day = 29;
				} else
					day = 28;
			} else if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
				day = 30;
			}
		}
		String y = year + "";
		String m = "";
		String d = "";
		if (month < 10)
			m = "0" + month;
		else
			m = month + "";
		if (day < 10)
			d = "0" + day;
		else
			d = day + "";
		return y + "-" + m;
	}

	public static String getDiff(String formart, int num) {

		Calendar curr = Calendar.getInstance();
		curr.set(Calendar.MONTH, curr.get(Calendar.MONTH) + num);
		Date date = curr.getTime();
		SimpleDateFormat df = new SimpleDateFormat(formart);// 日期格式
		String dateFormart = df.format(date);
		return dateFormart;
	}

	public static String getFormartDate(Date createTime, String format) {
		SimpleDateFormat df = new SimpleDateFormat(format);
		String dateFromart = df.format(createTime);
		return dateFromart;
	}

	public static int getMonth(String startDate, String endDate) {
		@SuppressWarnings("deprecation")
		Date start = new Date(startDate);
		@SuppressWarnings("deprecation")
		Date end = new Date(endDate);
		if (start.after(end)) {
			Date t = end;
			start = end;
			end = t;
		}
		Calendar startCal = Calendar.getInstance();
		startCal.setTime(start);
		Calendar endCal = Calendar.getInstance();
		endCal.setTime(end);
		Calendar tempCal = Calendar.getInstance();
		tempCal.setTime(end);
		tempCal.add(Calendar.DATE, 1);
		int year = endCal.get(Calendar.YEAR) - startCal.get(Calendar.YEAR);
		int month = endCal.get(Calendar.MONTH) - startCal.get(Calendar.MONTH);
		if ((startCal.get(Calendar.DATE) == 1) && (tempCal.get(Calendar.DATE)) == 1) {
			return year * 12 + month + 1;
		} else if ((startCal.get(Calendar.DATE) != 1) && (tempCal.get(Calendar.DATE)) == 1) {
			return year * 12 + month;
		} else if ((startCal.get(Calendar.DATE) == 1) && (tempCal.get(Calendar.DATE)) != 1) {
			return year * 12 + month;
		} else {
			return (year * 12 + month - 1) < 0 ? 0 : (year * 12 + month);
		}

	}

	public static long getDiffDate(Date date, Date end_date) {

		return (end_date.getTime() - date.getTime()) / (24 * 60 * 60 * 1000);
	}

	public static boolean getDiffTime(Date date, Date end_date) {

		if (date.getTime() + 10 * 1000 * 60 > end_date.getTime()) {
			return false;
		}
		return true;
	}

	public static boolean getDiffTime(Date date, Date end_date, long diff) {
		// 24 * 60 * 1000 * 60
		if (date.getTime() + diff > end_date.getTime()) {
			return false;
		}
		return true;
	}

	// 获取当天失效时间 单位(秒)
	public static Long getFailureTime() {
		Long time = 0l;
		try {
			DateFormat nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			DateFormat specifyTime = new SimpleDateFormat("yyyy-MM-dd");
			Date d1 = nowTime.parse(specifyTime.format(new Date()) + " 23:59:59");
			Date d2 = nowTime.parse(nowTime.format(new Date()));
			Long diff = d1.getTime() - d2.getTime();
			time = diff / 1000;
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return time;
	}

	/**
	 * @date 2014年7月11日 判断两个日期是否同一天 hq
	 */
	public static boolean isSameDay(Date day1, Date day2) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String ds1 = sdf.format(day1);
		String ds2 = sdf.format(day2);
		if (ds1.equals(ds2)) {
			return true;
		} else {
			return false;
		}
	}

	public static String getNowTime() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		return sdf.format(new Date());
	}

	/**
	 * 取得某天前30天的日期
	 * 
	 * @return
	 */
	public static Date get30DaysAgoDay() {
		String dateStr = getStringDate("yyyy-MM-dd");
		Date d = strToDate(dateStr, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d);
		date.add(Calendar.DAY_OF_MONTH, -30);
		return new Date(date.getTimeInMillis());
	}

	/**
	 * @author lv
	 * @date 2015年4月16日
	 * @desc 字符串转时间轴
	 */
	public static String str2DateTime(String date, String format) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			Date d = sdf.parse(date);
			long t = d.getTime();
			return String.valueOf(t);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取最近四个季度第一天
	 * 
	 * @return
	 */
	public static List<Long> getFourQuarter() {
		List<Long> res = new ArrayList<Long>();
		Date now = new Date();
		String dateStr = "";
		int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(now));
		int month = Integer.parseInt(new SimpleDateFormat("MM").format(now));
		if (month <= 3) {
			dateStr = year + "-01-01";
		} else if (month <= 6) {
			dateStr = year + "-04-01";
		} else if (month <= 9) {
			dateStr = year + "-07-01";
		} else {
			dateStr = year + "-10-01";
		}

		Date d1 = strToDate(dateStr, "yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(d1);
		res.add(date.getTimeInMillis());
		System.out.println(date.getTime());
		date.add(Calendar.MONTH, -3);
		res.add(date.getTimeInMillis());
		System.out.println(date.getTime());
		date.add(Calendar.MONTH, -3);
		res.add(date.getTimeInMillis());
		System.out.println(date.getTime());
		date.add(Calendar.MONTH, -3);
		res.add(date.getTimeInMillis());
		System.out.println(date.getTime());
		return res;
	}

	/**
	 * @author geyang 如何获得上周星期六的日期
	 * @return
	 */
	public static Date getLastWeekSunday() {

		Calendar date = Calendar.getInstance(Locale.CHINA);

		// date.setFirstDayOfWeek(Calendar.SATURDAY);//将每周第一天设为星期一，默认是星期天

		date.add(Calendar.WEEK_OF_MONTH, -1);// 周数减一，即上周

		date.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);// 日子设为星期天

		return date.getTime();

	}

	public static Date getLastWeekSunday(int week) {

		Calendar date = Calendar.getInstance(Locale.CHINA);

		// date.setFirstDayOfWeek(Calendar.SATURDAY);//将每周第一天设为星期一，默认是星期天

		date.add(Calendar.WEEK_OF_MONTH, week);// 周数减一，即上周

		date.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);// 日子设为星期天

		return date.getTime();

	}

	/**
	 * 获取当前日期前几天
	 * 
	 * @return
	 */
	public static String getDayBefore(String datet, int day) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 小写的mm表示的是分钟
		Calendar now = null;
		try {
			java.util.Date date = sdf.parse(datet);
			now = Calendar.getInstance();
			now.setTime(date);
			now.set(Calendar.DATE, now.get(Calendar.DATE) + day);

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String da = sdf.format(now.getTime());
		return da;

	}

	public static Date getDayBefore(int day) {
		Date date = new Date();
		Calendar now = Calendar.getInstance();
		now.setTime(date);
		now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
		return now.getTime();
	}

	public static Date getMinutesBefore(int m, Date date) {
		Calendar now = Calendar.getInstance();
		now.setTime(date);
		now.set(Calendar.MINUTE, now.get(Calendar.MINUTE) + m);
		return now.getTime();
	}

	public static Date getHourBefore(int hour) {
		Calendar now = null;
		now = Calendar.getInstance();
		now.setTime(new Date());
		now.set(Calendar.HOUR, now.get(Calendar.HOUR) - hour);
		return now.getTime();

	}

	/**
	 * 比较两个日期之间的大小
	 * 
	 * @param d1
	 * @param d2
	 * @return 前者大于后者返回true 反之false
	 * @throws ParseException
	 */
	public static boolean compareDate(String t1, String t2) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 小写的mm表示的是分钟
			Date d1 = null;
			Date d2 = null;
			d1 = sdf.parse(t1);
			d2 = sdf.parse(t2);
			Calendar c1 = Calendar.getInstance();
			Calendar c2 = Calendar.getInstance();
			c1.setTime(d1);
			c2.setTime(d2);
			int result = c1.compareTo(c2);
			if (result >= 0)
				return true;
			else
				return false;

		} catch (Exception e) {
			return false;
		}
	}

	public static boolean compareDate(Date t1, Date t2) {
		try {
			Calendar c1 = Calendar.getInstance();
			Calendar c2 = Calendar.getInstance();
			c1.setTime(t1);
			c2.setTime(t2);

			int result = c1.compareTo(c2);
			if (result >= 0)
				return true;
			else
				return false;
		} catch (Exception e) {
			return false;
		}
	}

	public static Date monthBefer(Date dt, int num) {
		Date dt1 = new Date();
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(dt);
		rightNow.add(Calendar.YEAR, 0);// 日期减
		rightNow.add(Calendar.MONTH, -num);// 日期加
		rightNow.add(Calendar.DAY_OF_YEAR, 0);// 日期加
		dt1 = rightNow.getTime();
		return dt1;
	}

	public static String getDatePoor(Date endDate, Date nowDate) {

		long nd = 1000 * 24 * 60 * 60;
		long nh = 1000 * 60 * 60;
		long nm = 1000 * 60;
		long ns = 1000;
		// 获得两个时间的毫秒时间差异
		long diff = endDate.getTime() - nowDate.getTime();
		// 计算差多少天
		long day = diff / nd;
		// 计算差多少小时
		long hour = diff % nd / nh;
		// 计算差多少分钟
		long min = diff % nd % nh / nm;
		// 计算差多少秒//输出结果
		long sec = diff % nd % nh % nm / ns;
		String desc = sec + "秒";
		if (min != 0) {
			desc = min + "分钟" + desc;
		}
		if (hour != 0) {
			desc = hour + "小时" + desc;
		}
		if (day != 0) {
			desc = day + "天" + desc;
		}
		return desc;
	}

	/**
	 * 2015年10月21日 lvjianqing 计算时间差（分钟）
	 */
	public static int getDiffMinute(String time1, String time2, String format) {
		int difftime;
		try {
			// 时间差
			SimpleDateFormat simpleDate = new SimpleDateFormat(format);
			Date d1 = null;
			Date d2 = null;
			d1 = simpleDate.parse(time1);
			d2 = simpleDate.parse(time2);
			// 毫秒ms
			long diff = d2.getTime() - d1.getTime();
			long diffHours = diff / 1000 / 60;
			difftime = new Long(diffHours).intValue();
			return difftime;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 两个时间之间相差距离多少天
	 * 
	 * @param one
	 *            时间参数 1：
	 * @param two
	 *            时间参数 2：
	 * @return 相差天数
	 */
	public static long getDistanceDays(String str1, String str2) throws Exception {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date one;
		Date two;
		long days = 0;
		try {
			one = df.parse(str1);
			two = df.parse(str2);
			long time1 = one.getTime();
			long time2 = two.getTime();
			long diff;
			if (time1 < time2) {
				diff = time2 - time1;
			} else {
				diff = time1 - time2;
			}
			days = diff / (1000 * 60 * 60 * 24);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return days;
	}

	public static long getDistanceDays(Date one, Date two) throws Exception {
		long days = 0;
		long time1 = one.getTime();
		long time2 = two.getTime();
		long diff;
		if (time1 < time2) {
			diff = time2 - time1;
		} else {
			diff = time1 - time2;
		}
		days = diff / (1000 * 60 * 60 * 24);
		return days;
	}

	public static String setDateFormat(String last_time) {
		SimpleDateFormat sdf;
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		String time = "";
		try {
			if (last_time.indexOf(".") > 0) {
				sdf = new SimpleDateFormat("yyyy.MM.dd");

				Date date = sdf.parse(last_time);
				time = sdf1.format(date);

			} else if (last_time.indexOf("/") > 0) {
				sdf = new SimpleDateFormat("yyyy/MM/dd");
				Date date = sdf.parse(last_time);
				time = sdf1.format(date);
			} else {
				Date date = sdf1.parse(last_time);
				time = sdf1.format(date);
			}
		} catch (Exception e) {
			return last_time;
		}

		return time;
	}

	public static String getFirstDayCurrYear() {

		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_YEAR, 1);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		Date FD = calendar.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		String dateStr = sdf.format(FD);
		return dateStr;
	}

	public static Timestamp dateTotimestamp(Date date) {
		String time = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		time = sdf.format(date);
		Timestamp ts = Timestamp.valueOf(time);
		return ts;
	}

	public static String[] getLast12Months(String time) {

		String[] last12Months = new String[12];

		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Date date = null;
		try {
			date = sdf.parse(time);// "2016-12"
		} catch (Exception e) {
			e.printStackTrace();
		}
		cal.setTime(date);
		cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1); // 要先+1,才能把本月的算进去</span>
		for (int i = 0; i < 12; i++) {
			cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); // 逐次往前推1个月
			last12Months[11 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1);
		}

		return last12Months;
	}

	public static Date nextMonthFirstDate(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Calendar calendar = Calendar.getInstance();
		try {
			calendar.setTime(sdf.parse(date));
		} catch (Exception e) {
			e.printStackTrace();
		}
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.add(Calendar.MONTH, 1);
		return calendar.getTime();
	}

	// 根据当前的日期获取当前一周的时间
	public static List<Date> dateToWeek(Date mdate) {
		@SuppressWarnings("deprecation")
		int b = mdate.getDay();
		if (b == 0) {
			b = 7;
		}
		Date fdate;
		List<Date> list = new ArrayList<Date>();
		Long fTime = mdate.getTime() - b * 24 * 3600000;
		for (int a = 1; a <= 7; a++) {
			fdate = new Date();
			fdate.setTime(fTime + (a * 24 * 3600000)); // 一周从周日开始算，则使用此方式
			// fdate.setTime(fTime + ((a-1) * 24*3600000)); //一周从周一开始算，则使用此方式
			list.add(a - 1, fdate);
		}
		return list;
	}

	public static List<String> getdatebymonth(String time) {
		List<String> list = new ArrayList<String>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
			Calendar cal = Calendar.getInstance();// 获得当前日期对象
			cal.clear();// 清除信息
			cal.setTime(sd.parse(time));

			// cal.set(Calendar.YEAR,year);
			// cal.set(Calendar.MONTH,month-1);//1月从0开始
			cal.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天

			// System.out.println("##########___" + sdf.format(cal.getTime()));
			list.add(sdf.format(cal.getTime()));
			int count = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
			for (int j = 0; j <= (count - 2); j++) {
				cal.add(Calendar.DAY_OF_MONTH, +1);
				list.add(sdf.format(cal.getTime()));
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	// 根据时间获取本周的所有日期
	private static final int FIRST_DAY = Calendar.MONDAY;

	public static List<String> printWeekdays(String time) {
		List<String> list = new ArrayList<String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		try {
			calendar.setTime(sdf.parse(time));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		setToFirstDay(calendar);
		for (int i = 0; i < 7; i++) {
			list.add(printDay(calendar));
			calendar.add(Calendar.DATE, 1);
		}
		return list;
	}

	private static void setToFirstDay(Calendar calendar) {
		while (calendar.get(Calendar.DAY_OF_WEEK) != FIRST_DAY) {
			calendar.add(Calendar.DATE, -1);
		}
	}

	private static String printDay(Calendar calendar) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String time = dateFormat.format(calendar.getTime());
		return time;
	}

	// 获取某月的第一天
	public static Date getMonthFirst(String date) throws Exception {
		SimpleDateFormat spd = new SimpleDateFormat("yyyy-MM");
		Date time = spd.parse(date);
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, time.getYear() + 1900);
		cal.set(Calendar.MONTH, time.getMonth());
		cal.set(Calendar.DAY_OF_MONTH, 1);
		Date firstDate = cal.getTime();
		return firstDate;
	}

	// 获取某月的最后一天
	public static Date getMonthLast(String date) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Date time = sdf.parse(date);
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, time.getYear() + 1900);
		cal.set(Calendar.MONTH, time.getMonth() + 1);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		cal.add(Calendar.DAY_OF_MONTH, -1);
		Date firstDate = cal.getTime();
		return firstDate;
	}

	public static List<Date> getMdatefandl(String startTime) {
		List<Date> dlist = new ArrayList<Date>();
		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
			Date start = null;
			Date end = null;
			if (startTime != null && !"".equals(startTime)) {
				start = df.parse(startTime);
			} else {
				start = DateUtil.getFirstDayCurrMonth();
			}

			if (startTime != null && !"".equals(startTime)) {
				Calendar ca = Calendar.getInstance();
				ca.setTime(df.parse(startTime));
				ca.set(Calendar.DATE, 1);
				ca.add(Calendar.MONTH, 1);
				ca.add(Calendar.DATE, -1);
				end = ca.getTime();
			} else {
				Calendar ca = Calendar.getInstance();
				ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
				end = ca.getTime();
			}
			dlist.add(start);
			dlist.add(end);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dlist;
	}

	public static int getMonthSpace(String date1, String date2) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// String str1 = "2012-02";
		// String str2 = "2010-01";
		Calendar bef = Calendar.getInstance();
		Calendar aft = Calendar.getInstance();
		bef.setTime(sdf.parse(date1));
		aft.setTime(sdf.parse(date2));
		int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
		int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
		System.out.println(Math.abs(month + result));
		return month + result;
	}
	
	/**
	 * @Title: 方法名：nextMonthFirstDate_two
	 * @Description: 功能描述：获取下个月的一号
	 * @author hqD ☺ ^o^
	 * @date 2018年1月3日 下午3:16:50
	 * @param @return
	 * @return String 返回类型
	 * @throws ParseException
	 */
	public static String nextMonthFirstDate_two(String strDate) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		Date sourceDate = format.parse(strDate);
		calendar.setTime(sourceDate);
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.add(Calendar.MONTH, 1);
		return format.format(calendar.getTime());
	}
	
	/**
	 * @Title: 方法名：LongToDate
	 * @Description: 功能描述：毫秒数转时间
	 * @author hqD ☺ ^o^
	 * @date 2017年12月13日 上午9:45:19
	 * @param @param dateMs
	 * @param @return    
	 * @return String    返回类型
	 */
	public static String LongToDate(long dateMs) {
		Date date = new Date(dateMs);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(date);
	}

	public static void main(String[] args) throws Exception {
		/*
		 * 
		 * String[] a= DateUtil.getLast12Months("2016-12"); for(int i=0;i<a.length;i++){
		 * System.out.println(DateUtil.getLast12Months("2016-12")[i]); }
		 */
		System.out.println(LongToDate(1512779532000L));
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		System.err.println(getTommorrowDay());
//		List<String> weeks = DateUtil.printWeekdays("2017-02-08");
//		for (int i = 0; i < weeks.size(); i++) {
//
//			Date d = sdf.parse(weeks.get(i));
//			System.out.println(sdf.format(d));
//
//		}
//		System.out.println((DateUtil.getTommorrowDay1(sdf.parse(weeks.get(weeks.size() - 1)))).getTime() / 1000);
		/*
		 * List<String> list = DateUtil.getdatebymonth("2017-02"); for(int
		 * i=0;i<list.size();i++){ System.out.println(list.get(i)); }
		 */
		//System.out.println(sdf.format((getTommorrowDay1(new Date()))));
		/*
		 * System.out.println(DateUtil.getTommorrowDay1(formater.parse(formater.format(
		 * DateUtil.getMonthLast("2017-02")))).getTime()/1000);
		 * System.out.println(DateUtil.getBeforeDay(formater.parse(formater.format(
		 * DateUtil.getMonthFirst("2017-02")))).getTime()/1000);
		 * System.out.println(formater.parse("2017-04-11").getTime()/1000);
		 */
	}

}
